﻿@namespace BootstrapBlazor.Components
@typeparam TItem
@inherits BootstrapComponentBase

<div @attributes="@AdditionalAttributes" class="@ClassString">
    @if (HeaderTemplate != null)
    {
        <div class="listview-header">
            @HeaderTemplate
        </div>
    }
    <div class="@BodyClassString">
        @if (BodyTemplate != null)
        {
            if (GroupName == null)
            {
                foreach (var item in Rows)
                {
                    <div class="listview-item" @onclick="@(e => OnClick(item))">
                        @BodyTemplate(item)
                    </div>
                }
            }
            else if (Collapsible)
            {
                <Collapse IsAccordion="IsAccordion" OnCollapseChanged="OnCollapseChanged!">
                    <CollapseItems>
                        @RenderCollapsibleItems(GroupName)
                    </CollapseItems>
                </Collapse>
            }
            else
            {
                foreach (var key in GetGroupItems(GroupName))
                {
                    <div @key="@key.GroupName" class="accordion-item">
                        <div class="accordion-header">@key.GroupName</div>
                        <div class="accordion-body">
                            @foreach (var item in key.Items)
                            {
                                <div class="listview-item" @onclick="@(e => OnClick(item))">
                                    @BodyTemplate(item)
                                </div>
                            }
                        </div>
                    </div>
                }
            }
        }
    </div>
    @if (FooterTemplate != null || Pageable)
    {
        <div class="listview-footer">
            @if (FooterTemplate != null)
            {
                @FooterTemplate
            }
            else if (Pageable)
            {
                <Pagination PageCount="@PageCount" PageIndex="@PageIndex" OnPageLinkClick="@OnPageLinkClick"></Pagination>
            }
        </div>
    }
</div>

@code {
    RenderFragment RenderItem((object? GroupName, IOrderedEnumerable<TItem> Items) key, int index) =>
    @<CollapseItem Text="@GetGroupName(key.GroupName)" IsCollapsed="IsCollapsed(index, key.GroupName)">
        @foreach (var item in key.Items)
        {
            <div class="listview-item" @onclick="@(e => OnClick(item))">
                @if(BodyTemplate != null)
                {
                    @BodyTemplate(item)
                }
            </div>
        }
    </CollapseItem>;
}
